package cn.dengta.webapp.trade.entity;

import java.util.List;

import cn.dengta.webapp.base.dao.GeoPoint;
import cn.dengta.webapp.base.dao.GeoPointTypeHandler;
import cn.dengta.webapp.base.entity.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.codeplayer.util.Cmp;
import me.codeplayer.util.StringUtil;

/**
 * 地区信息表
 *
 * @author HCG
 * @since 2023-03-15
 */
@Setter
@Getter
@Accessors(chain = true)
@TableName(value = "dt_area", autoResultMap = true)
public class Area extends BaseEntity {

	public static final Integer PROVINCE_LEVEL = 1;
	public static final Integer CITY_LEVEL = 2;
	public static final Integer DISTRICT_LEVEL = 3;

	/** 地区名称 */
	String name;
	/** 父级编码 */
	Long parentId;
	/** 位置信息 */
	@TableField(typeHandler = GeoPointTypeHandler.class)
	GeoPoint location;
	/** 行政级别：1=省；2=市；3=区 */
	Integer level;
	/** 地区全路径名称 */
	String fullName;

	@TableField(exist = false)
	List<Area> children;

	public String getCode() {
		return id.toString();
	}

	public boolean isProvince() {
		return Cmp.eq(level, PROVINCE_LEVEL);
	}

	public boolean isCity() {
		return Cmp.eq(level, CITY_LEVEL);
	}

	public boolean isDistrict() {
		return Cmp.eq(level, DISTRICT_LEVEL);
	}

	public static Integer mapLevel(String level) {
		if (StringUtil.isEmpty(level)) {
			return null;
		}
		return switch (level) {
			case "province" -> PROVINCE_LEVEL;
			case "city" -> CITY_LEVEL;
			case "district" -> DISTRICT_LEVEL;
			default -> null;
		};
	}

	@Getter
	public static class CacheNode {

		/** 地区名称 */
		final String name;
		/** 地区全路径名称 */
		final String fullName;
		/** 经度 */
		final Double lon;

		public CacheNode(Area area) {
			this.name = area.name;
			this.fullName = area.fullName;
			this.lon = area.location == null ? null : area.location.getLon();
		}

	}

	public static final String NAME = "name";
	public static final String PARENT_ID = "parent_id";
	public static final String LOCATION = "location";
	public static final String LEVEL = "level";
	public static final String FULL_NAME = "full_name";

}
